package com.javathread.th2.forkjoin.sum;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class SumArray {
		private static class SumTask extends RecursiveTask<Long>{
			
			private final static int THRESHOLD = MakArray.ARRAY_LENGTH/10;
			private long[] src;//表示我们要实际统计的数组
			private int fromIndex;//开始统计的下标
			private int toIndex;//统计到哪里结束的下标
			
			public SumTask(long[] src, int fromIndex, int toIndex) {
				this.src = src;
				this.fromIndex = fromIndex;
				this.toIndex = toIndex;
			}
			

			@Override
			protected Long compute() {
				if (toIndex - fromIndex < THRESHOLD) {
					long count = 0L;
					for (int i = fromIndex; i < toIndex; i++) {
						count  = count + src[i];
					}
					return count;
				} else {
					int mid = (fromIndex + toIndex)/2;
					SumTask left = new SumTask(src, fromIndex, mid);
					SumTask right = new SumTask(src, mid+1, toIndex);
					invokeAll(left,right);
					return left.join() + right.join();
				}
			}
			
		}
		
		public static void main(String[] args) {
			ForkJoinPool pool = new ForkJoinPool();
			long[] src = MakArray.makeArray();
			
			SumTask innerFind = new SumTask(src,0,src.length-1);
			long start = System.currentTimeMillis();
			pool.invoke(innerFind);//同步调用
			System.out.println("Task is Running");
			
			System.out.println("总和 ="+innerFind.join() + " 花费时间:" + (System.currentTimeMillis() - start ) +" 毫秒");
		}
}
